from django import forms
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator
from app01 import models
import random
from django.shortcuts import render, HttpResponse
from utils.tencent.sms import send_sms_single
from django.conf import settings

# Create your views here.


def send_sms(request):
    """发送短信
        ?tpl=login -->用户登录 
        ?tpl=register ->用户注册ID
    """
    code = random.randrange(1000, 9999)
    tpl = request.GET.get('tpl')
    template_id = settings.TENCENT_SMS_TEMPLATE.get(tpl)
    if not template_id:
        return HttpResponse('模板不存在')
    res = send_sms_single('xxxxxxx', template_id, [code, ])
    # print(res)
    if res['result'] == 0:
        return HttpResponse('成功')
    else:
        return HttpResponse(res['errmsg'])


'''RegexValidator是一个对象，接收两个参数
    第一个参数是正则表达式，对用户提交的数据进行校验
    第二个是如果正则表达式匹配没通过，返回一个报错信息
'''


class RegisterModelForm(forms.ModelForm):
    # 重写mobile_phone字段属性，Django没有提供手机号字段，所以只能定义正则
    mobile_phone = forms.CharField(label='手机号', validators=[
                                   RegexValidator(r'^(1[3|4|5|6|7|8|9])\d{9}$', '手机号格式错误'), ])
    password = forms.CharField(label='密码', widget=forms.PasswordInput())

    confirm_password = forms.CharField(
        label='再次输入密码', widget=forms.PasswordInput())

    code = forms.CharField(label='验证码', widget=forms.TextInput())

    class Meta:
        model = models.UserInfo
        fields = ['username', 'email', 'password',
                  'confirm_password', 'mobile_phone', 'code']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'
            field.widget.attrs['placeholder'] = '请输入%s' % (field.label,)


def register_sms(request):
    form = RegisterModelForm()
    return render(request, 'app01/register.html', {'form': form})
